
make.plot.of.saturated.regressions = function(reg.list, 
                                              x.lab = "Relative tactical incentive (deciles)", 
                                              y.lab = "Proportion voting tactically", 
                                              y.lims = c(0,1), 
                                              y.line.loc = 7.5, 
                                              pchs = rep(19, length(reg.list)), 
                                              offsets = seq(-.15, .15, length = length(reg.list)), 
                                              pt.cex = .5, 
                                              point.cols = rep("black", length(reg.list)), 
                                              confint.cols = point.cols, 
                                              line.cols = point.cols, 
                                              confint.ltys = rep(2, length(reg.list)), 
                                              ltys = 1:(length(reg.list)), 
                                              x.vals = 1:length(coef(reg.list[[1]])),  # equal spacing of the points
                                              plot.confints = F,
                                              error.bar.confint.plot = T,
                                              default.axis = F,
                                              axis.with.no.labels = F,
                                              x.labels = paste0("D", x.vals),
                                              tones = c(.3, .4, .5, .6, .7),
                                              lwds = rep(1, length(reg.list)),
                                              x.lims = NULL,
                                              new = TRUE){
  
  if(new){
    plot(x = range(x.vals), y = c(0,1), type = "n", axes = F, xlab = x.lab, ylab = y.lab, ylim = y.lims, xlim = x.lims)
    if(default.axis){
      axis(1)
    }else if(axis.with.no.labels){
      axis(1, at = c(-100000000, 10000000), labels = c("Should not", "see these"))
    }else{
      axis(1, at = x.vals, labels = x.labels) 		
    }
    axis(2)
    abline(v = y.line.loc, lty = 2, col = "gray") # identifies where tau turns positive
  }
  
  for(j in 1:length(reg.list)){
    # plot point estimates 
    points(x.vals + offsets[j], coef(reg.list[[j]]), pch = pchs[j], col = point.cols[j], cex = pt.cex)
    # connect them
    lines(x = x.vals + offsets[j], y = coef(reg.list[[j]]), col = line.cols[j], lty = ltys[j], lwd = lwds[j])  # 1:10
    # plot the confidence intervals
    if(plot.confints){
      # I want to do this with polygon instead. 
      if(error.bar.confint.plot){
        for(i in 1:length(x.vals)){
          lines(x = c(x.vals[i], x.vals[i]) + offsets[j], y = confint(reg.list[[j]])[i,], lty = confint.ltys[j], col = confint.cols[j])
        }							
      }else{
        ci.mat = confint(reg.list[[j]])
        the.tone = tones[j] # .25 + .12*j
        polygon(x = c(x.vals, rev(x.vals)) + offsets[j], y = c(ci.mat[,1], rev(ci.mat[,2])), col = rgb(the.tone, the.tone, the.tone, alpha = .3), border = F)  # 1:nrow(ci.mat), nrow(ci.mat):1) + offsets[j]
      }
    }				
  }
  
}



make.plot.of.saturated.regressions.2 = function(reg.list, 
                                              x.lab = "Relative tactical incentive (deciles)", 
                                              y.lab = "Proportion voting tactically", 
                                              y.lims = c(0,1), 
                                              y.line.loc = 7.5, 
                                              pchs = rep(19, length(reg.list)), 
                                              offsets = seq(-.15, .15, length = length(reg.list)), 
                                              pt.cex = .5, 
                                              point.cols = rep("black", length(reg.list)), 
                                              confint.cols = point.cols, 
                                              line.cols = point.cols, 
                                              confint.ltys = rep(2, length(reg.list)), 
                                              ltys = 1:(length(reg.list)), 
                                              x.vals = 1:nrow(reg.list[[1]]),  # equal spacing of the points
                                              plot.confints = F,
                                              error.bar.confint.plot = T,
                                              default.axis = F,
                                              axis.with.no.labels = F,
                                              x.labels = paste0("D", x.vals),
                                              tones = c(.3, .4, .5, .6, .7),
                                              lwds = rep(1, length(reg.list)),
                                              x.lims = NULL,
                                              new = T){
  
  if(new){
      plot(x = range(x.vals), y = c(0,1), type = "n", axes = F, xlab = x.lab, ylab = y.lab, ylim = y.lims, xlim = x.lims)
    if(default.axis){
      axis(1)
    }else if(axis.with.no.labels){
      axis(1, at = c(-100000000, 10000000), labels = c("Should not", "see these"))
    }else{
      axis(1, at = x.vals, labels = x.labels) 		
    }
    axis(2)
    abline(v = y.line.loc, lty = 2, col = "gray") # identifies where tau turns positive
  
  }
  for(j in 1:length(reg.list)){
    # plot point estimates 
    point.estimates = reg.list[[j]]$estimate
    ses = reg.list[[j]]$std.error
    points(x.vals + offsets[j], point.estimates, pch = pchs[j], col = point.cols[j], cex = pt.cex)
    # connect them
    lines(x = x.vals + offsets[j], y = point.estimates, col = line.cols[j], lty = ltys[j], lwd = lwds[j])  # 1:10
    # plot the confidence intervals
    if(plot.confints){
      ci.mat = point.estimates + 1.96*cbind(-ses, ses)
      the.tone = tones[j]
      polygon(x = c(x.vals, rev(x.vals)) + offsets[j], y = c(ci.mat[,1], rev(ci.mat[,2])), col = rgb(the.tone, the.tone, the.tone, alpha = .3), border = F)  
    }				
  }
}



access_list_element = function(l, element){
  l[[element]]
}
  
make_intx_plot = function(list.of.reg.result.mats, regnames = c("edu", "edu", "income", "income", "age", "age", "gender", "left.fp"), varnames = paste0("I(tau.vec > 0)TRUE:", c("edu_cat2", "edu_cat3", "income_cat2", "income_cat3", "age_cat2", "age_cat3", "gender2", "left.fp2")),
model.labels = c("Model 1: utility from party, leader, and candidate ratings", "Model 2: utility from party ratings only", "Model 3: utility from party ratings only (no imputation)"), xlabs = c("Education:\nsome higher ed", "Education:\nuniversity+", "Income:\n$60k-$100k", "Income:\n$100k+", "Age:\n37-56", "Age:\n57+", "Gender:\nfemale", "Preferred party:\nLib (vs NDP)"), offsets = c(-.2, 0, .2), pchs = c(19, 21, 23), legend.loc = "topright", ylims = c(-.05, .2), horiz = F){
  
  plot(c(.25, 8.75), ylims, type = "n", axes = F, xlab = "", ylab = "Difference in strategic responsiveness compared to baseline")
  axis(1, at = 1:8, labels = xlabs, line = 0, cex.axis = .7, padj = 1)
  abline(h = 0, lty = 2)
  axis(2)
  
  shade.col = rgb(.8, .8, .8, alpha = .5)
  polygon(x = c(2.5, 4.5, 4.5, 2.5), y = c(-100, -100, 100, 100), col = shade.col, border = F)
  polygon(x = c(6.5, 7.5, 7.5, 6.5), y = c(-100, -100, 100, 100), col = shade.col, border = F)
  
  # cycling over the models
  # for each model we want 
  for(j in 1:length(offsets)){
    offset = offsets[j]
    for(k in 1:8){
      the.result.mat = list.of.reg.result.mats[[j]][[regnames[k]]]
      the.coef = the.result.mat[the.result.mat$term == varnames[k], "estimate"]
      the.se = the.result.mat[the.result.mat$term == varnames[k], "std.error"]
      lines(x = rep(k + offset, 2), y = the.coef + c(-1, 1)*1.96*the.se, col = "gray")
      points(x = k + offset, y = the.coef, pch = pchs[j])
    }
  }
  
  legend(legend.loc, pch = pchs, legend = model.labels, bg = "white", cex = .85, lty = 1, horiz = horiz)

}


### for plotting distribution of tau

ecdf_by_party = function(tau_vec, fave_party_mat, parties = c("lib", "con", "ndp", "bq", "grn"), party_names = c("Lib", "Con", "NDP", "BQ", "Green"), cols = c("red", "blue", "orange", "lightblue", "green"), the.lwd = 3){
  
  plot(range(tau_vec, na.rm = T), c(0,1), type = "n", xlab = expression(paste("Max expected utility gain from tactical vote (", tau, ")", sep = "")), ylab = "Cumulative density", main = "", axes = F)
  axis(1);axis(2)
  xs = seq(min(tau_vec, na.rm = T), max(tau_vec, na.rm = T), length = 1000)
  for(i in 1:length(parties)){
    the.ecdf = ecdf(tau_vec[fave_party_mat[,i] == 1])
    lines(xs, the.ecdf(xs), lty = i, lwd = the.lwd, col = cols[i])
  }
  abline(h = c(0, .2, .4, .6, .8, 1), col = "gray")
  legend("left", ncol = 2, lty = 1:length(parties), lwd = the.lwd, legend = party_names, bg = "white", col = cols)
  
}

tau_cat_freq_by_party = function(tau_cats, fave_party_mat, parties = c("lib", "con", "ndp", "bq", "grn"), party_names = c("Lib", "Con", "NDP", "BQ", "Green"), cols = c("red", "blue", "orange", "lightblue", "green"), the.lwd = 3){
  plot(c(.5,10.5), c(0,.4), type = "n", xlab = expression(paste("Category of ", tau, sep = "")), ylab = "Frequency", main = "", axes = F)
  axis(1, at = 1:10, labels = 1:10, cex.axis = .8);axis(2, cex.axis = .8)
  xs = 1:10
  for(i in 1:length(parties)){
    this.use = fave_party_mat[,i] == 1 
    freqs = as.vector(table(as.factor(tau_cats)[this.use]))/sum(this.use, na.rm = T)
    lines(xs, freqs, lty = i, lwd = the.lwd, col = cols[i])
  }
  abline(h = .1, col = "gray")
  abline(v = 7.5, col = "gray", lty = 3)
  legend("topleft", ncol = 2, lty = 1:length(parties), lwd = the.lwd, legend = party_names, bg = "white", col = cols)
}


